<template>
  <div>
    <DynamicTable
      row-key="id"
      header-title="班级管理"
      :data-request="Api.student.classPage"
      :columns="columns"
      bordered
      size="small"
    >
      <template #toolbar>
        <a-button type="primary" @click="openClassModal({})"> 新增 </a-button>
      </template>
    </DynamicTable>
  </div>
</template>

<script lang="ts" setup>
  import type { TableColumn } from '@/components/core/dynamic-table';
  import { useTable } from '@/components/core/dynamic-table';
  import { useFormModal } from '@/hooks/useModal/';
  import Api from '@/api/';
  import { formatToDateTime } from '@/utils/dateUtil';

  defineOptions({
    name: 'StudentClasses',
  });

  interface TableListItem {
    id: number;
    name: string;
    createTime: string;
  }

  const [DynamicTable, dynamicTableInstance] = useTable({
    pagination: {
      pageSize: 10,
      showSizeChanger: true,
      showQuickJumper: true,
    },
  });
  const [showModal] = useFormModal();

  const formSchemas = [
    {
      field: 'className',
      label: '班级名称',
      component: 'Input',
      required: true,
    },
  ];

  /**
   * @description 打开新增/编辑弹窗
   */
  const openClassModal = async (record: Partial<TableListItem>) => {
    const [formRef] = await showModal({
      modalProps: {
        title: `${record.id ? '编辑' : '新增'}班级`,
        width: '50%',
        onFinish: async (values) => {
          if (record.id) {
            await Api.student.classUpdate({ id: record.id, ...values });
          } else {
            await Api.student.classCreate(values);
          }
          dynamicTableInstance?.reload();
        },
      },
      formProps: {
        labelWidth: 100,
        schemas: formSchemas,
      },
    });
    formRef?.setFieldsValue(record);
  };

  const delRowConfirm = async (record: TableListItem) => {
    await Api.studentClasses.classDelete({ id: record.id });
    dynamicTableInstance?.reload();
  };

  const columns: TableColumn<TableListItem>[] = [
    {
      title: '班级ID',
      dataIndex: 'id',
      width: 80,
      hideInSearch: true,
    },
    {
      title: '班级名称',
      dataIndex: 'className',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 180,
      hideInSearch: true,
      customRender: ({ text }) => formatToDateTime(text),
    },
    {
      title: '操作',
      width: 130,
      dataIndex: 'ACTION',
      hideInSearch: true,
      fixed: 'right',
      actions: ({ record }) => [
        {
          label: '编辑',
          onClick: () => openClassModal(record),
        },
        // {
        //   label: '删除',
        //   popConfirm: {
        //     title: '你确定要删除吗？',
        //     placement: 'left',
        //     onConfirm: () => delRowConfirm(record),
        //   },
        // },
      ],
    },
  ];
</script>
